import config from '@/config/index.js';
import Vue from 'vue';
const vue = new Vue();

const install = (Vue, vm) => {
	// 此为自定义配置参数，具体参数见上方说明
	Vue.prototype.$u.http.setConfig({
		baseUrl: config.baseUrl,
		loadingText: '努力加载中~',
		dataType: 'json',
		originalData: true,
		loadingTime: 1500,
		header: {
			'content-type': 'application/json;charset=UTF-8',
		},
	});

	// 请求拦截部分，如配置，每次请求前都会执行，见上方说明
	Vue.prototype.$u.http.interceptor.request = (configData) => {
		uni.showToast({
			title: '加载中',
			icon: 'loading',
		});
		if (configData.url != '/dealer/login') {
			configData.header['appId'] = uni.getStorageSync('userKey').appId;
			configData.header['authorization'] = uni.getStorageSync('userKey').authorization;
			// configData.header['appId'] = '1720023233575415809';
			// configData.header['authorization'] = 'eyJhbGciOiJIUzUxMiIsInppcCI6IkRFRiJ9.eNokytEKwjAMQNF_yfMKSZO0zf6mWytMQWWtMhD_fRVf77kfuPYNZkDDzIsUZ2syJ5dizjSIq0WDIueAwjBBey1jpugRPXtmjSqkCW3Y1tqw_rjVu2t1f9f9F3OHmSJS8sZEE9Tj-Q9GGom-JwAAAP__.xi7z93fRuhvZRf6_2VauKqmIVvKG6JeZ6QnZUnQv3OnjtKkS9YtG7ADxg2iwJxr9NeoPrFeHOTzwtixFp1EWCw';
			configData.header['platform'] = 'seller';
		}
		return configData;
	};

	// 响应拦截，如配置，每次请求结束都会执行本方法
	Vue.prototype.$u.http.interceptor.response = (res) => {
		// console.log(res);
		if (res.statusCode * 1 === 200) {
			uni.hideToast();
			if (res.data.resultCode * 1 === 0) {
				return res.data;
			} else if (res.data.resultCode == 51003 || res.data.resultCode == 34008) {
				uni.showToast({
					title: res.data.resultInfo,
					icon: 'none',
					duration: 2000,
				});
				return res.data;
			} else if (res.data.resultCode == 12006 || res.data.resultCode == 12005) {
				uni.navigateTo({
					url: '/pages/login/index',
				});
			} else if (res.data.resultCode == 11000) {
				uni.showToast({
					title: res.data.resultInfo,
					icon: 'none',
					duration: 2000,
				});
				return false;
			} else if (res.data.resultCode == 12017) {
				uni.showToast({
					title: res.data.resultInfo,
					icon: 'error',
					duration: 2000,
				});
			} else {
				uni.showToast({
					title: res.data.resultInfo || '喝口水吧，让数据飞一会，请稍后再试',
					icon: 'none',
				});
				return false;
			}
		} else {
			uni.hideToast();
			switch (res.statusCode * 1) {
				case 500:
					uni.showToast({
						title: '喝口水吧，让数据飞一会，请稍后再试',
						icon: 'none',
					});
					break;
				case 401:
					uni.showToast({
						title: '没有权限',
						icon: 'none',
					});
					break;
				case 404:
					uni.showToast({
						title: '找不到接口',
						icon: 'none',
					});
					break;
				case 413:
					uni.showToast({
						title: '上传失败',
						icon: 'none',
					});
					break;
				default:
					uni.showToast({
						title: '喝口水吧，让数据飞一会，请稍后再试',
						icon: 'none',
					});
					break;
			}
			return false;
		}
	};
};

export default {
	install,
};